package job.work.utils;

import com.alibaba.druid.util.StringUtils;
import job.work.domain.response.*;
import job.work.domain.system.entity.pojo.model.SystemUser;
import job.work.framework.ExceptionCast;
import job.work.service.system.service.SystemService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: qinmushequ
 * @description: 从token获取用户名
 * @author: zzy
 * @create: 2020-01-09 11:28
 **/

@Service
public class TokenUtil {

    @Resource
    private SystemService systemService;
    @Resource
    private HttpServletRequest request;

    //管理员绑定areaId
    public String areaId="450300";

    //获取token 并且返回用户对象
    public SystemUser token() {
        String requestTokenHeader = request.getHeader("token");

        if (StringUtils.isEmpty(requestTokenHeader)){
            ExceptionCast.cast(AuthCode.AUTH_LOGIN_TOKEN_TIME);
        }
        String token = requestTokenHeader.substring(7);
        if (StringUtils.isEmpty(token)){
            ExceptionCast.cast(AuthCode.AUTH_LOGIN_TOKEN_TIME);
        }
        String username = JwtTokenUtils.getUsername(token);
        if (StringUtils.isEmpty(username)) {
            ExceptionCast.cast(AuthCode.AUTH_LOGIN_TOKEN_TIME);
            return null;
        } else {
            SystemUser byUsername = systemService.findSystemUserName(username);
            return byUsername;
        }
    }


    //获取token 并且返回角色ID
    public Integer tokenRole(HttpServletRequest request, JwtTokenUtils jwtTokenUtil) {
        String requestTokenHeader = request.getHeader("X-Token");
        String Xtoken = requestTokenHeader.substring(7);
        return Integer.parseInt(JwtTokenUtils.getUserRole(Xtoken));
    }

    public  ResponseResult pageResult(List all, int pageNum, int pageSize){
        //开始分页
        List  userList = (List) all.stream().skip((pageNum- 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        //返回参数
        PageResult queryResult = queryResult(userList, all.size());
        return new ResponseResult<>(CommonCode.SUCCESS, queryResult);
    }

    public PageResult queryResult(List list, long size){
        PageResult queryResult = new PageResult();
        //获取查询结果集
        queryResult.setRows(list);
        //获取查询总条数
        queryResult.setTotal(size);

        return queryResult;
}

}
